//
//  ArticleViewController.m
//  Molian
//
//  Created by wansong on 3/31/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//

#import "ArticleViewController.h"
#import "RecommendUserCell.h"
#import "CommentViewController.h"
#import "MLUserDataViewController.h"


@interface ArticleViewController ()<UMSocialUIDelegate,UIWebViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong)UIWebView *webView;

///喜欢按钮
@property (nonatomic, strong)UIButton *likeBtn;
@property (nonatomic)BOOL status;//yes喜欢,no,不喜欢
@property (nonatomic)BOOL is;

@end

@implementation ArticleViewController
{
    UIImageView *titleImgView;
    NSInteger loading;
    CGFloat titleImgHeight;
    UIImageView *cellbackground;
    UILabel *titleLabel;
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [HUD hideFromViewAnimated:YES];
    
}


#pragma mark - lifecycle

- (void)viewDidLoad {
    self.is = NO;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.article.title;
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    [AVAnalytics event:@"文章阅读"]; // 通知服务器一个点击事件。
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, DeviceWidth, DeviceHeight-64)];
    self.webView.delegate = self;
    self.webView.scrollView.delegate = self;
    self.webView.alpha = 0;
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.scrollView.backgroundColor = [UIColor whiteColor];
   self.webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake( -64, 0, 40, 0);//滚动条偏移量
    [self.webView setScalesPageToFit:YES];
    [self.view addSubview:self.webView];
    
    //    titleImgHeight = EqualHeight(320, 640, DeviceWidth);
   // titleImgHeight = EqualHeight(260, 608, DeviceWidth-20);
      titleImgHeight = EqualHeight(260, 608, DeviceWidth);
    
    // 标题图片
    titleImgView = [[UIImageView alloc]init];
    titleImgView.clipsToBounds = YES;
    [titleImgView setContentMode:UIViewContentModeScaleAspectFill];
    [titleImgView sd_setImageWithURL:[NSURL URLWithString:self.article.title_img.url]placeholderImage:[UIImage imageWithColor:[UIColor whiteColor]]];
    
    cellbackground = [[UIImageView alloc]initWithFrame:CGRectMake(0, titleImgView.frame.size.height-45, DeviceWidth, 45)];
    cellbackground.image = [UIImage imageNamed:@"profile_title_shadow"];
    cellbackground.alpha = 0.7;
    [titleImgView addSubview:cellbackground];
    
    // 标题
    titleLabel = [[UILabel alloc]init];
    titleLabel.frame = CGRectMake(10, titleImgView.frame.size.height-30, DeviceWidth-20, 30);
    titleLabel.text = self.article.title;
    titleLabel.font = [UIFont fontWithName:FontName size:16];
    titleLabel.textColor = [UIColor whiteColor];
    [titleImgView addSubview:titleLabel];
    
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(titleImgHeight, 0, 40, 0);
    
    // 重置headerView高度
    [titleImgView setFrame:CGRectMake(0, -titleImgHeight, DeviceWidth, titleImgHeight)];
    [self.webView.scrollView addSubview:titleImgView];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]];
    [_webView loadRequest:request];
    
    if (self.article.address) {
        NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:self.article.address]];
        [self.webView loadRequest:request];
    }
    
    [self bottomView];
    //保存阅读记录
    [Utils saveArticleReadObjectID:self.article.objectId];
    
    [self.article incrementKey:@"readCount" byAmount:[NSNumber numberWithInteger:+1]];
    [self.article saveInBackground];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset  = scrollView.contentOffset.y;
    if (yOffset < -titleImgHeight) {
        CGRect f = titleImgView.frame;
        f.origin.y = yOffset;
        f.size.height =  -yOffset;
        titleImgView.frame = f;
        cellbackground.frame = CGRectMake(0, titleImgView.frame.size.height-45, DeviceWidth, 45);
        titleLabel.frame = CGRectMake(10, titleImgView.frame.size.height-30, DeviceWidth-20, 30);
    }
}

- (void) webViewDidStartLoad:(UIWebView *)webView
{
    if (loading <=5) {
        loading ++;
        [HUD setOnViewWithTitle:@"请求中" animated:YES];
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [HUD hideFromViewAnimated:YES];
    
    if (self.article.address) {
        NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:self.article.address]];
        [self.webView loadRequest:request];
    }
}

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    [HUD hideFromViewAnimated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.webView.alpha = 1;
    });
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"=== %@", request.URL.absoluteString); //可以直接拿到发送请求的网址
    NSString *urlStr = request.URL.absoluteString;
    
    // 格式 neng://loadUrl/blog.csdn.net  协议/方法/网址
    //判断链接中的协议头,如果是neng://, 则进行相关操作
    if ([urlStr hasPrefix:@"molian://"]) {
        //拿到除去协议头的后部
        NSString *urlContent = [urlStr substringFromIndex:[@"molian://" length]];
        NSLog(@"%@", urlContent);
        
        //用/来拆分字符串
        NSArray *urls = [urlContent componentsSeparatedByString:@"/"];
        NSLog(@"拆分的结果为:%@", urls);
        
        //取出方法名
        if (urls.count != 2) {
            return NO;
        }
        NSString *funName = [NSString stringWithFormat:@"%@:", urls[0]]; //带参数的方法,加冒号
        
        SEL callFun = NSSelectorFromString(funName);
        //取消警告
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self performSelector:callFun withObject:urls[1]]; //将blog.csdn.net作为参数传入
# pragma clang diagnostic pop
        NSLog(@"方法名为%@, 传入参数为%@", funName, urls[1]);
        
        return NO;
    }
    return YES;
}

- (void)viewUser:(NSString *)obj
{
    if (obj==nil||[obj isEqualToString:@"undefined"]) {
        return;
    }
    
    
    [HUD setOnViewWithTitle:@"" animated:YES];
    AVQuery *chatUser = [MLUser query];
    [chatUser whereKey:@"objectId" equalTo:obj];
    [chatUser findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        [HUD hideFromViewAnimated:YES];
        
        if (objects&&objects.count) {
            MLUser *showUser = objects[0];
            MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
            userInfoVC.userData = showUser;
            
            [self.navigationController pushViewController:userInfoVC animated:YES];

        }
    }];
}
- (void)goToUserData
{
   
    if (self.article&&self.article.userId&&self.article.userId.length) {
        [self viewUser:self.article.userId];
    }
    
}
-(void)bottomView
{
    /****** 底部按钮 ******/
    UIView *bottomView = [[UIView alloc]init];
    bottomView.backgroundColor = [UIColor whiteColor];
    bottomView.frame = CGRectMake(0, DeviceHeight-40, DeviceWidth, 40);
    CGFloat btnWidth = DeviceWidth/3;
    
    // 分享按钮
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame = CGRectMake(0, 0, btnWidth, 40);
    [shareBtn setImage:[UIImage imageNamed:@"icon_share"] forState:UIControlStateNormal];
    [shareBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    shareBtn.adjustsImageWhenDisabled = YES;
    shareBtn.titleLabel.textColor = [UIColor blackColor];
    shareBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    shareBtn.titleLabel.font = [UIFont fontWithName:FontName size:11];
    [shareBtn setTitle:@" 查看资料" forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(goToUserData) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:shareBtn];
    
    
    //评论按钮
    UIButton *commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    commentBtn.frame = CGRectMake(btnWidth, 0, btnWidth, 40);
    [commentBtn setImage:[UIImage imageNamed:@"icon_comment"] forState:UIControlStateNormal];
    [commentBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    commentBtn.adjustsImageWhenDisabled = YES;
    commentBtn.titleLabel.textColor = [UIColor blackColor];
    commentBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    commentBtn.titleLabel.font = [UIFont fontWithName:FontName size:11];
    if (self.article.commentCount<=0) {
        self.article.commentCount = 0;
    }
    NSString *commentStr = [NSString stringWithFormat:@" 评论 %ld", (long)self.article.commentCount];
    [commentBtn setTitle:commentStr forState:UIControlStateNormal];
    [commentBtn addTarget:self action:@selector(goToComment) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:commentBtn];
    
    
    //喜欢按钮
    self.likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.likeBtn.frame = CGRectMake(DeviceWidth-btnWidth, 0, btnWidth, 40);
    //[self.likeBtn setImage:[UIImage imageNamed:@"icon_like_no_selected"] forState:UIControlStateNormal];
    //[self.likeBtn setImage:[UIImage imageNamed:@"icon_like_selected"] forState:UIControlStateDisabled];
    [self.likeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    self.likeBtn.adjustsImageWhenDisabled = YES;
    self.likeBtn.titleLabel.textColor = [UIColor blackColor];
    self.likeBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    self.likeBtn.titleLabel.font = [UIFont fontWithName:FontName size:11];
    if (self.article.likeCount<=0) {
        self.article.likeCount = 0;
    }
    NSString *likeStr = [NSString stringWithFormat:@" 喜欢 %@",[[ShareData shareData].likeArticlesDic objectForKey: self.article.objectId]];
    if(!likeStr){
        likeStr = [NSString stringWithFormat:@"%ld",(long)self.article.likeCount];
        [[ShareData shareData].likeArticlesDic setObject:likeStr forKey:self.article.objectId];
    }
    [self.likeBtn setTitle:likeStr forState:UIControlStateNormal];
    [self.likeBtn addTarget:self action:@selector(likeArticle) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.likeBtn];
    
    // 设置文章的喜欢的状态
    //BOOL isLiked = NO;
    self.status = NO;
    if ([Utils isLoveArticleObjectId:self.article.objectId]) {
        self.status = YES;
    }
    [self setLikeBtnImage];
    //    if (isLiked) {
    //        [self.likeBtn setEnabled:NO];
    //    } else {
    //        [self.likeBtn setEnabled:YES];
    //    }
    
    // 分隔线
    for (int i = 0; i < 3; i++) {
        UIView *Line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DeviceWidth, 1)];
        Line.backgroundColor = RGBA(229, 229, 229, 1);
        if (i>=1) {
            Line.frame = CGRectMake(btnWidth*i, 5, 0.5, 30);
        }
        [bottomView addSubview:Line];
    }
    
    // 添加bottomView
    [self.view addSubview:bottomView];
    
}
- (void)setLikeBtnImage
{
    if (self.status) {
        [self.likeBtn setImage:[UIImage imageNamed:@"icon_like_selected"] forState:UIControlStateNormal];
        
    }else{
        [self.likeBtn setImage:[UIImage imageNamed:@"icon_like_no_selected"] forState:UIControlStateNormal];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}


#pragma mark - table delegate


// 去评价
- (void)goToComment {
    [AVAnalytics event:@"文章评论"]; // 通知服务器一个点击事件。
    if (![Utils userinit:self]) {
        return;
    }
    CommentViewController *commentViewController = [[CommentViewController alloc]init];
    commentViewController.hidesBottomBarWhenPushed = YES;
    commentViewController.article = self.article;
    [self.navigationController pushViewController:commentViewController animated:YES];
}
// 去分享
- (void)goToShare {
    [AVAnalytics event:@"文章分享"]; // 通知服务器一个点击事件。
    
    //如果需要分享回调,请将delegate对象设置self,并实现下面的回调方法
    [UMSocialSnsService handleOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://pocketsweet.com/share?articleId=%@",self.article.objectId]]];
    
    [UMSocialData defaultData].extConfig.wechatSessionData.url = [NSString stringWithFormat:@"http://pocketsweet.com/share?articleId=%@",self.article.objectId];
    
    [UMSocialData defaultData].extConfig.qqData.url = [NSString stringWithFormat:@"http://pocketsweet.com/share?articleId=%@",self.article.objectId];
    
    [UMSocialData defaultData].extConfig.title = self.title;
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:UM_KEY
                                      shareText:self.article.intro
                                     shareImage:titleImgView.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone,UMShareToDouban,UMShareToRenren,UMShareToSms,nil]
                                       delegate:self];
}

//下面得到分享完成的回调
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    NSLog(@"didFinishGetUMSocialDataInViewController with response is %@",response);
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        [HUD Prompt:@"分享成功!"];
    }else{
        //        [Utils HUDImage:nil Title:@"失败" Content:@"分享失败" Timer:2];
        
    }
}

//用户分享或者关闭分享页面的回调方法
-(void)didCloseShakeView
{
    [HUD Prompt:@"分享取消!"];
}


// 喜欢文章
- (void)likeArticle {
    [AVAnalytics event:@"文章喜欢"]; // 通知服务器一个点击事件。
    if (![Utils userinit:self]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    [ShareData shareData].isRecommend = YES;
    if (self.is) {
        //
    }else{
        self.is = YES;
        //开始请求数据,设置为不交互
        if (self.status) {
            //当前是喜欢,改变为不喜欢
            AVQuery *q = [MLArticleLike query];
            [q whereKey:@"user" equalTo:[MLUser currentUser]];
            [q whereKey:@"article" equalTo:self.article];
            [q deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if(!error){
                    // 标记已喜欢的状态
                    NSInteger i = [[[ShareData shareData].likeArticlesDic objectForKey:self.article.objectId] integerValue];
                    // 标记已喜欢的状态
                    
                    i--;
                    if (i<=0) {
                        i = 0;
                    }
                    self.status = NO;
                    [self setLikeBtnImage];
                    
                    NSString *likeStr = [NSString stringWithFormat:@" 喜欢 %ld", (long)i];
                    [[ShareData shareData].likeArticlesDic setObject:[NSString stringWithFormat:@"%ld", (long)i] forKey:self.article.objectId];
                    [Utils removeObjectForLoveArticleObjectID:self.article.objectId];
                    [self.likeBtn setTitle:likeStr forState:UIControlStateNormal];
                    [self.article incrementKey:@"likeCount" byAmount:[NSNumber numberWithInteger:-1]];
                    
                    self.article.fetchWhenSave = true;
                    
                    [self.article saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (!error) {
                            // 添加到喜欢的列表里面
                        }
                    }];
                    
                    self.is = NO;//请求数据结束
                }else{
                    self.is = NO;//请求数据结束
                }
                
                
            }];
            
        }else{
            //当前是不喜欢,改变为喜欢
            //开始请求
            
            MLArticleLike *like = [MLArticleLike object];
            like.user = [MLUser currentUser];
            like.article = self.article;
            [like saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                self.is = NO;//请求数据结束
                if (!error) {
                    // article表增加一个喜欢的次数
                   
                    self.status = YES;
                    [self setLikeBtnImage];
                    NSInteger i = [[[ShareData shareData].likeArticlesDic objectForKey:self.article.objectId] integerValue];
                    // 标记已喜欢的状态
                    i++;
                    
                    NSString *likeStr = [NSString stringWithFormat:@" 喜欢 %ld", (long)i];
                    [[ShareData shareData].likeArticlesDic setObject:[NSString stringWithFormat:@"%ld", (long)i] forKey:self.article.objectId];
                    // 添加到喜欢的列表里面
                    [Utils savePassLoveArticleObjectID:self.article.objectId];
                    [self.likeBtn setTitle:likeStr forState:UIControlStateNormal];
                    
                    [self.article incrementKey:@"likeCount" byAmount:[NSNumber numberWithInteger:+1]];
                    self.article.fetchWhenSave = true;
                    [self.article saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (!error) {
                            // 添加到喜欢的列表里面
                            
                        }
                    }];
                }
            }];
        }
    }
}

@end
